package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.heima.aliyun.GreenImageScan;
import com.heima.aliyun.GreenTextScan;
import com.heima.common.exception.CustException;
import com.heima.feigns.AdminFeign;
import com.heima.model.common.constants.message.PublishArticleConstants;
import com.heima.model.common.constants.wemedia.WemediaConstants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.vos.WmNewsContentAndImage;
import com.heima.utils.common.SensitiveWordUtil;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class WmNewsAutoScanServiceImpl implements WmNewsAutoScanService {
    @Value("${file.oss.web-site}")
    String webSite;

    @Autowired
    private WmNewsMapper wmNewsMapper;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void autoScanWmNews(Integer id) {
        // 1. 校验参数  id
        if (id == null) {
            log.error("自动审核文章失败 文章id为空");
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "文章id不能为空");
        }
        // 2.  根据id查询出文章信息
        WmNews wmNews = wmNewsMapper.selectById(id);
        if (wmNews == null) {
            log.error("自动审核文章失败 文章不存在 id:{}", id);
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "文章不存在");
        }
        // 3.  检查文章状态   状态: 1
        if (!wmNews.getStatus().equals(WemediaConstants.WM_NEWS_SUMMIT_STATUS)) {
            log.error("自动审核文章失败 文章不在待审核状态 id:{}", id);
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW, "文章不在待审核状态");
        }
        // 4.  抽取出文章的所有  文本内容  和  图片url
        WmNewsContentAndImage contentAndImages = handleTextAndImages(wmNews);
        // 5.  敏感词审核   不通过 状态: 2
        boolean isSensitive = handleSensitive(contentAndImages.getContent(),wmNews);
        if (!isSensitive) {
            log.error("文章自动审核未通过，内容中包含敏感词");
            return;
        }
        // 6.  阿里云 文本审核   block: 2    review  3
        boolean isText = handleText(contentAndImages.getContent(),wmNews);
        if (!isText) {
            log.error("文章自动审核未通过，内容中包含违规信息");
            return;
        }
        // 7.  图片审核   block: 2    review  3
        boolean isImage = handleImages(contentAndImages.getImages(),wmNews);
        if (!isImage) {
            log.error("文章自动审核未通过，图片中包含违规信息");
            return;
        }
        // 8.  修改状态: 8
        updateWmNews(wmNews,WmNews.Status.SUCCESS.getCode(), "自动审核通过");
        // 9. TODO 发布延时任务，用于发布文章
        long publishTime = wmNews.getPublishTime().getTime();
        long nowTime = System.currentTimeMillis();
        long time = publishTime - nowTime;
        rabbitTemplate.convertAndSend(PublishArticleConstants.DELAY_DIRECT_EXCHANGE,
                PublishArticleConstants.PUBLISH_ARTICLE_ROUTE_KEY,
                wmNews.getId(),
                message -> {
                    message.getMessageProperties().setHeader("x-delay", time<=0 ? 0 : time);
                    return message;
                }
        );
        log.info("成功发送  发布文章消息   待发布的文章id: {}",wmNews.getId());

    }

    @Autowired
    GreenImageScan greenImageScan;
    /**
     * 图片审核 阿里云
     * @param images
     * @param wmNews
     * @return
     */
    private boolean handleImages(List<String> images, WmNews wmNews) {
        boolean flag = false;
        try {
            Map map = greenImageScan.imageUrlScan(images);
            String suggestion = (String) map.get("suggestion");
            switch (suggestion) {
                case "block":
                    updateWmNews(wmNews, WmNews.Status.FAIL.getCode(), "图片违规");
                    break;
                case "pass":
                    flag = true;
                    break;
                case "review":
                    updateWmNews(wmNews, WmNews.Status.ADMIN_AUTH.getCode(), "图片包含不确定的信息,需要进一步人工审核");
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
            updateWmNews(wmNews,WmNews.Status.ADMIN_AUTH.getCode(),"阿里云审核调用失败，转为人工审核");
        }
        return flag;
    }

    @Autowired
    GreenTextScan greenTextScan;
    /**
     * 阿里云 文本审核   block: 2    review  3
     * @param content
     * @param wmNews
     * @return
     */
    private boolean handleText(String content, WmNews wmNews) {
        boolean flag = false;
        try {
            Map map = greenTextScan.greenTextScan(content);
            String suggestion = (String) map.get("suggestion");
            switch (suggestion){
                case "block":
                    updateWmNews(wmNews,WmNews.Status.FAIL.getCode(),"内容中含有违规信息");
                    break;
                case "pass":
                    flag = true;
                    break;
                case "review":
                    updateWmNews(wmNews,WmNews.Status.ADMIN_AUTH.getCode(), "内容中包含不确定的信息,需要进一步人工审核");
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
            updateWmNews(wmNews,WmNews.Status.ADMIN_AUTH.getCode(),"阿里云审核调用失败，转为人工审核");
        }
        return flag;
    }

    @Autowired
    AdminFeign adminFeign;
    /**
     * 敏感词审核
     * @param content
     * @param wmNews
     * @return
     */
    private boolean handleSensitive(String content, WmNews wmNews) {
        boolean flag = true;
        ResponseResult<List<String>> sensitivesResult = adminFeign.sensitives();
        if (!sensitivesResult.checkCode()) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
        }
        List<String> sensitives = sensitivesResult.getData();
        if (CollectionUtils.isNotEmpty(sensitives)) {
            SensitiveWordUtil.initMap(sensitives);
            Map<String, Integer> map = SensitiveWordUtil.matchWords(content);
            if (CollectionUtils.isNotEmpty(map)) {
                updateWmNews(wmNews,WmNews.Status.FAIL.getCode(),"内容中包括敏感词:"+map);
                flag=false;
            }
        }
        return flag;
    }

    @Autowired
    WmNewsService wmNewsService;

    /**
     * 修改文章状态
     * @param wmNews
     * @param fail
     * @param s
     */
    private void updateWmNews(WmNews wmNews, short fail, String s) {
        wmNews.setStatus(fail);
        wmNews.setReason(s);
        wmNewsService.updateById(wmNews);

    }

    /**
     * 抽取出文章的所有  文本内容  和  图片url
     *
     * @param wmNews
     * @return
     */
    private WmNewsContentAndImage handleTextAndImages(WmNews wmNews) {
        String contentResult = wmNews.getContent();
        if (StringUtils.isBlank(contentResult)) {
            log.error("自动审核文章失败 文章内容不存在 id:{}", wmNews.getId());
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "文章内容不存在");
        }
        //获取内容文本
        List<Map> maps = JSON.parseArray(contentResult, Map.class);
        String content = maps.stream()
                .filter(m -> (m.get("type").equals("text")))
                .map(m -> (String) m.get("value"))
                .collect(Collectors.joining("_hmtt_"));
        //标题
        content += "_hmtt_" + wmNews.getTitle();

        //内容图片
        List<String> images = maps.stream()
                .filter(m -> (m.get("type").equals("image")))
                .map(m -> (String)m.get("value"))
                .collect(Collectors.toList());
        //获封面图片
        String imageStr = wmNews.getImages();
        if (StringUtils.isNoneBlank(imageStr)) {
            List<String> imageList = Arrays.stream(imageStr.split(","))
                    .map(url -> webSite + url)
                    .collect(Collectors.toList());
            images.addAll(imageList);
        }
        images = images.stream().distinct().collect(Collectors.toList());
        WmNewsContentAndImage contentAndImage = new WmNewsContentAndImage();
        contentAndImage.setContent(content);
        contentAndImage.setImages(images);
        return contentAndImage;
    }
}
